package com.example.closethreadgracefully.controller;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class MyRunnable3 extends Thread {

    private volatile boolean stop = false;

    CloseableHttpClient httpClient;

    public void setStop(boolean stop) {
        this.stop = stop;
    }

    @Override
    public void run() {
        /*如果任务不停止*/
        while (Boolean.FALSE.equals(stop)) {

            for (int i = 0; i < 1000; i++) {
                if (Boolean.FALSE.equals(stop)) {
                    System.out.println("i = " + i);
                    /*Request www.baidu.com*/
                    httpClient = HttpClients.createDefault();
                    try {
                        httpClient.execute(new HttpGet("http://www.baidu.com"));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.out.println("任务停止");
                    return;
                }
            }
            /*执行完成业务后，休眠一会 然后继续下一轮执行 例如，休息30分钟*/
            try {
                /*但是如果使用的是 变量来控制现成的运行或者是停止 休眠的时候如何控制呢？只能等休眠结束
                 * 再次走到 while的时候判断才能结束么？ 分多次休眠呢？*/
                for (int i = 0; i < 300; i++) {
                    System.out.println("休息10秒钟");
                    Thread.sleep(1000L * 10);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }
}
